package com.mystudy.leetcode.base;


import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: infoalgorithm
 * @description:
 * @author: zhouzhilong
 * @create: 2019-08-09 12:25
 **/
public class TreeNodeUtils {
    /**
     * 根据层序遍历的结果生成二叉树，注意，非二分搜索树
     *
     * @param arrays
     * @return
     */
    public static TreeNode generateTwoTrees(Integer[] arrays) {
        TreeNode root = null;
        if (arrays == null || arrays.length == 0) {
            return null;
        }
        root = new TreeNode(arrays[0]);
        generate(root, 0, arrays);
        return root;
    }

    /**
     * 生成以node为根的树
     *
     * @param node
     */
    private static void generate(TreeNode node, int index, Integer[] arrays) {
        int leftIndex = leftChildIndex(index);
        int rightIndex = rightChildIndex(index);
        if (leftIndex < arrays.length) {
            Integer left = arrays[leftIndex];
            if (left != null) {
                node.left = new TreeNode(left);
                generate(node.left, leftIndex, arrays);
            } else {
                node.left = null;
            }
        }
        if (rightIndex < arrays.length) {
            Integer right = arrays[rightIndex];
            if (right != null) {
                node.right = new TreeNode(right);
                generate(node.right, rightIndex, arrays);
            } else {
                node.right = null;
            }
        }
    }

    public static void show(TreeNode node) {
        StringBuilder result = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(node);
        result.append("[");
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            result.append(cur.val);
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
            if (!queue.isEmpty()) {
                result.append(",");
            }
        }
        result.append("]");
        System.out.println(result.toString());

        }


    private static int leftChildIndex(int index) {
        return 2 * index + 1;
    }

    private static int rightChildIndex(int index) {
        return 2 * index + 2;
    }


}
